package com.yuexun.dhdoctor.module.meeting.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


import com.yuexun.dhdoctor.R;
import com.yuexun.dhdoctor.base.BaseKJActivity;
import com.yuexun.dhdoctor.base.model.impl.HelpModel;
import com.yuexun.dhdoctor.base.presenter.impl.HelpPresent;
import com.yuexun.dhdoctor.base.ui.IHelpView;
import com.yuexun.dhdoctor.config.AppConfig;
import com.yuexun.dhdoctor.module.email.adapter.MailFileAdapter;
import com.yuexun.dhdoctor.module.email.bean.MailFileBean;
import com.yuexun.dhdoctor.module.email.bean.MailFileDataBean;
import com.yuexun.dhdoctor.module.meeting.bean.MeetingBeanCheckBean;
import com.yuexun.dhdoctor.module.meeting.bean.MeetingCheckStateBean;
import com.yuexun.dhdoctor.module.meeting.bean.MeetingCheckStateBeanDate;
import com.yuexun.dhdoctor.module.meeting.bean.MeetingDetailBean;
import com.yuexun.dhdoctor.module.meeting.bean.MeetingDetailBeanDate;
import com.yuexun.dhdoctor.module.meeting.bean.MeetingSignStateEnum;
import com.yuexun.dhdoctor.module.meeting.model.impl.MeetingDetailModel;
import com.yuexun.dhdoctor.module.meeting.presenter.impl.MeetingDetailPresenter;
import com.yuexun.dhdoctor.module.meeting.ui.view.IMeetingDetailView;
import com.yuexun.dhdoctor.widget.FixedSwipeListView;

import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class Act_MeetingDetail extends BaseKJActivity implements IMeetingDetailView, IHelpView {

    @Bind(R.id.title)
    TextView tvTitle;
    @Bind(R.id.right)
    TextView meetingRightTv;
    @Bind(R.id.tv_meeting_theme)
    TextView tvMeetingTheme;
    @Bind(R.id.tv_meeting_date)
    TextView tvMeetingDate;
    @Bind(R.id.tv_meeting_location)
    TextView tvMeetingLocation;
    @Bind(R.id.tv_host)
    TextView tvHost;
    @Bind(R.id.tv_clerk)
    TextView tvClerk;
    @Bind(R.id.tv_participant)
    TextView tvParticipant;
    @Bind(R.id.tv_content)
    TextView tvContent;
    @Bind(R.id.flv_attachment)
    FixedSwipeListView flvAttachment;
    @Bind(R.id.btn_sign_in)
    Button btnSignIn;
    @Bind(R.id.tv_error)
    TextView tvError;

    private String meetingId;
    private int type;

    private MeetingDetailPresenter presenter;
    HelpPresent helpPresent;
    MeetingDetailBeanDate meetingDetailBeanDate;

    ArrayList<MailFileDataBean> mailFileDataBeans = new ArrayList<MailFileDataBean>();
    MailFileAdapter mailFileAdapter;
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    SimpleDateFormat daformatter = new SimpleDateFormat("MM-dd HH:mm");
    SimpleDateFormat dateformatter = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat timeformatter = new SimpleDateFormat("HH:mm");

    @Override
    public void setRootView() {
        setContentView(R.layout.act_meetingdetail);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        super.initData();
        tvTitle.setText("会议详情");
        meetingRightTv.setText("签到记录");
        meetingRightTv.setVisibility(View.VISIBLE);
        presenter = new MeetingDetailPresenter(new MeetingDetailModel(), this);
        helpPresent = new HelpPresent(new HelpModel(), this);
        meetingId = getIntent().getExtras().getString("meetingId");
        type = getIntent().getExtras().getInt("type");
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Bundle bun = getIntent().getExtras();
        if (bun != null) {
            Set<String> keySet = bun.keySet();
            for (String key : keySet) {
                String value = bun.getString(key);
                if (key.equals("meetingId")) {
                    meetingId = value;
                    initP();
                }
            }
        }
    }

    private void initP() {
        if (TextUtils.isEmpty(meetingId)) {
            Toast.makeText(aty, "会议详请求失败,请稍后再试", Toast.LENGTH_SHORT).show();
            return;
        }

        Map<String, String> params = new HashMap<>();
        params.put("sessionUuid", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("meetingId", meetingId);
        presenter.getMeetingDetail(params);
    }


    @OnClick({R.id.back, R.id.right, R.id.btn_sign_in})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.right:
                Intent resultIntent = new Intent(this, Act_Meeting_Sign.class);
                Bundle bundle = new Bundle();
                bundle.putString("meetingId", meetingId);
                resultIntent.putExtras(bundle);
                startActivity(resultIntent);
                break;
            case R.id.btn_sign_in:
                try {
                    long startTime = formatter.parse(meetingDetailBeanDate.getStarttime()).getTime();
                    if (System.currentTimeMillis() > startTime) {
                        Intent intent = new Intent(aty, Act_MeetingCheck.class);
                        intent.putExtra("type", 0);
                        startActivityForResult(intent, 1);
                    } else {
                        ViewInject.toast("签到时间会议时间与不符合！");
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                break;
        }
    }

    @Override
    public void showMeetingDetail(MeetingDetailBean meetingDetailBean) {
        if (meetingDetailBean.getStatus().equals("200")) {
            meetingDetailBeanDate = meetingDetailBean.getDatas().get(0);
            tvMeetingTheme.setText("会议主题：" + meetingDetailBeanDate.getMeetingName());

            try {
                Date start = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(meetingDetailBeanDate.getStarttime());
                Date end = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(meetingDetailBeanDate.getEndtime());


                if (dateformatter.parse(meetingDetailBeanDate.getStarttime()).equals(dateformatter.parse(meetingDetailBeanDate.getEndtime()))) {
                    tvMeetingDate.setText(daformatter.format(start) + " - " + timeformatter.format(end));
                } else {
                    tvMeetingDate.setText(daformatter.format(start) + " - " + daformatter.format(end));
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
//            tvMeetingDate.setText(meetingDetailBeanDate.getStarttime() + "-" + meetingDetailBeanDate.getEndtime());
            tvMeetingLocation.setText(meetingDetailBeanDate.getRoomName());
            tvHost.setText(meetingDetailBeanDate.getCompere());
            tvClerk.setText(meetingDetailBeanDate.getClerk());
            tvParticipant.setText(meetingDetailBeanDate.getParticipant());
            tvContent.setText(meetingDetailBeanDate.getContent());

//            try {
//                long endTime = formatter.parse(meetingDetailBeanDate.getEndtime()).getTime();
//                if (System.currentTimeMillis() > endTime) {
//                    meetingRightTv.setVisibility(View.GONE);
//                }
//            } catch (ParseException e) {
//                e.printStackTrace();
//            }

            if (meetingDetailBeanDate.getDigestUrl() != null && !meetingDetailBeanDate.getDigestUrl().isEmpty()) {
                String[] digestUrls = meetingDetailBeanDate.getDigestUrl().split(";");
                for (int i = 0; i < digestUrls.length; i++) {
                    if (digestUrls[i] != null && !digestUrls[i].isEmpty()) {
                        Map<String, String> params = new HashMap<>();
                        params.put("sessionUuid", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
                        params.put("fileUuid", digestUrls[i]);
                        helpPresent.getFileData(params);
                    }
                }
            }

            inquireSignState();
        } else if (meetingDetailBean.getStatus().equals("403") || meetingDetailBean.getStatus().equals("404")) {
            tvError.setText(meetingDetailBean.getMessage());
            tvError.setVisibility(View.VISIBLE);
            meetingRightTv.setVisibility(View.GONE);
        } else {
            ViewInject.toast(meetingDetailBean.getMessage());
        }
    }

    @Override
    public void showMeetingCheckState(MeetingCheckStateBean meetingCheckStateBean) {
        if (meetingCheckStateBean.getStatus().equals("200")) {
            MeetingCheckStateBeanDate meetingCheckStateBeanDate = meetingCheckStateBean.getDatas().get(0);
            MeetingSignStateEnum signStateEnum = MeetingSignStateEnum.valueOf(meetingCheckStateBeanDate.getSignState());

            switch (signStateEnum) {
                case NO_SIGN:
                    break;
                case SIGN_IN:
                    btnSignIn.setText(signStateEnum.getDescription());
                    break;
                case MEETING_OUT_OF_DATE:
                    btnSignIn.setText(signStateEnum.getDescription());
                    btnSignIn.setEnabled(false);
            }
            if (type == 1) {
                signIn(meetingId);
            }
        } else {
            ViewInject.toast(meetingCheckStateBean.getMessage());
        }
    }

    @Override
    public void showMeetingCheck(MeetingBeanCheckBean meetingBeanCheckBean) {
        if (meetingBeanCheckBean.getStatus().equals("200")) {
            ViewInject.toast("签到成功");
            btnSignIn.setText("已签到");
//            meetingRightTv.setEnabled(false);
        } else {
            ViewInject.toast(meetingBeanCheckBean.getMessage());
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case 1:
                    String result = data.getStringExtra("resultString");
                    if (TextUtils.isEmpty(result)) {
                        ViewInject.toast("扫描失败,请重新尝试");
                        return;
                    }

                    String signMeetingId;
                    try {
                        signMeetingId = result.split(":")[1];
                    } catch (Exception e) {
                        ViewInject.toast("会议二维码错误,请重新尝试");
                        return;
                    }
                    signIn(signMeetingId);
                    break;
            }
        }
    }

    private void signIn(String signMeetingId) {
        if (!meetingId.equals(signMeetingId)) {
            ViewInject.toast("您所签到的会议不是当前会议");
            return;
        }

        Map<String, String> params = new HashMap<>();
        params.put("sessionUuid", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("meetingId", signMeetingId);
        presenter.getMeetingCheck(params);
    }


    private void inquireSignState() {
        Map<String, String> params = new HashMap<>();
        params.put("sessionUuid", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("meetingId", meetingId);
        presenter.getMeetingCheckState(params);
    }

    @Override
    public void getFileData(MailFileBean mailFileBean) {
        if (mailFileBean.getStatus().equals("200")) {
            mailFileDataBeans.add(mailFileBean.getDatas().get(0));
            mailFileAdapter = new MailFileAdapter(this, mailFileDataBeans, false);
            flvAttachment.setAdapter(mailFileAdapter);
        } else {
            Log.e("jx", "文件信息获取失败");
        }
    }
}
